package daoImpl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import utility.Utility;
import dao.CustomerDAO;
import domain.Customer;

public class CustomerDaoImpl implements CustomerDAO {

	protected static Logger log = Logger.getLogger(CustomerDaoImpl.class);
	
	@Resource(name = "sessionFactory")
	SessionFactory sessionFactory;

	@Override
	public void addCustomer(Customer customer) {
		log.debug("Adding a new customer ...");
		Session session = Utility.getSession(sessionFactory);
		session.save(customer);
		log.debug("A new customer was added successfully!!!");
	}

	@Override
	public void editCustomer(Customer customer) {
		log.debug("Editting an existing customer : " + customer.getCustomerName() + " ...");
		Session session = Utility.getSession(sessionFactory);
		Customer existCust = (Customer) session.get(Customer.class, customer.getCustomerId());
		existCust.setAddress(customer.getAddress());
		existCust.setCustomerName(customer.getCustomerName());
		existCust.setPhone(customer.getPhone());
		existCust.setOrders(customer.getOrders());
		session.save(existCust);
		log.debug("Updated exist customer : " + existCust.getCustomerName());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> searchCustomer(String strSearch) {
		log.debug("Searching customer with string " + strSearch + " ...");
		Session session = Utility.getSession(sessionFactory);
		String strsearch = "FROM Customer where customerName like %:customerName%";
		Query query = session.createQuery(strsearch);
		query.setParameter("customerName", strSearch);
		List<Customer> searchResult = query.list();
		if (CollectionUtils.isNotEmpty(searchResult)) {
			log.debug("Retrun a list of customer has size : " + searchResult.size());
			return searchResult;
		} else {
			log.debug("No records has been found");
			return null;
		}
	}
}
